package com.drools.example.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.kie.api.KieServices;
import org.kie.api.builder.ReleaseId;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.AgendaGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.drools.example.model.Address;
import com.drools.example.model.Order;
import com.drools.example.model.User;
import com.drools.example.model.fact.AddressCheckResult;
import com.drools.example.service.EmailService;
import com.drools.example.service.ReloadDroolsRulesService;

/**
 * 功能描述,该部分必须以中文句号结尾。
 *
 * @author panqingcui
 * @create 2018-08-21 09:07
 */
@Controller
public class RuleController {
    private static final Logger LOGGER = LoggerFactory.getLogger(RuleController.class);
    @Resource
    private ReloadDroolsRulesService rules;
    @Resource
    private EmailService emailService;

    @ResponseBody
    @RequestMapping(value = "/address", method = RequestMethod.GET)
    public void test(int num) {
        Address address = new Address();
        address.setPostcode("" + num);
        LOGGER.info("address {}", address);
        KieSession kieSession = ReloadDroolsRulesService.kieContainer.newKieSession();
        kieSession.setGlobal("emailService", emailService);
        AddressCheckResult result = new AddressCheckResult();
        kieSession.insert(address);
        kieSession.insert(result);
        //
        AgendaGroup agendaGroup = kieSession.getAgenda().getAgendaGroup("test-group");
        agendaGroup.setFocus();
        int ruleFiredCount = kieSession.fireAllRules();
        kieSession.destroy();
        LOGGER.info("触发了 {} 条规则", ruleFiredCount);
        if (result.isPostCodeResult()) {
            LOGGER.info("规则校验通过");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/order", method = RequestMethod.GET)
    public void order() {
        // 通过单例创建KieServices
        KieServices kieServices = KieServices.Factory.get();
        // 1 /releaseId maven 引用
         ReleaseId releaseId = kieServices.newReleaseId("com.drools.example", "named-kiesession", "0.0.1-SNAPSHOT");
         KieContainer kieContainer = kieServices.newKieContainer(releaseId);
        // 2.
      //   KieContainer kieContainer = kieServices.getKieClasspathContainer();
         KieSession kieSession = kieContainer.newKieSession();
//        KieSession kieSession = ReloadDroolsRulesService.kieContainer.newKieSession();
        AgendaGroup agendaGroup = kieSession.getAgenda().getAgendaGroup("test-group");
        agendaGroup.setFocus();
       //  KieSession kieSession = kieContainer.newKieSession();
        try {
            List<Order> orders = getInitData();
            for (Order order : orders) {
                kieSession.insert(order);
                int count = kieSession.fireAllRules();
                LOGGER.info("order:----->{},{}", count, order);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
        }
        kieSession.dispose();
    }

    private List<Order> getInitData() throws Exception {
        List<Order> orderList = new ArrayList<Order>();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        {
            Order order = new Order();
            order.setAmout(80);
            order.setBookingDate(df.parse("2015-07-01"));
            User user = new User();
            user.setLevel(1);
            user.setName("Name1");
            order.setUser(user);
            order.setScore(111);
            orderList.add(order);
        }
        {
            Order order = new Order();
            order.setAmout(200);
            order.setBookingDate(df.parse("2015-07-02"));
            User user = new User();
            user.setLevel(2);
            user.setName("Name2");
            order.setUser(user);
            orderList.add(order);
        }
        {
            Order order = new Order();
            order.setAmout(800);
            order.setBookingDate(df.parse("2015-07-03"));
            User user = new User();
            user.setLevel(3);
            user.setName("Name3");
            order.setUser(user);
            orderList.add(order);
        }
        {
            Order order = new Order();
            order.setAmout(1500);
            order.setBookingDate(df.parse("2015-07-04"));
            User user = new User();
            user.setLevel(4);
            user.setName("Name4");
            order.setUser(user);
            orderList.add(order);
        }
        return orderList;
    }

    /**
     * 从数据加载最新规则
     * @return
     * @throws java.io.IOException
     */
    @ResponseBody
    @RequestMapping(value = "/reload", method = RequestMethod.GET)
    public String reload() throws IOException {
        rules.reload();
        return "ok";
    }

    /**
     * 生成随机数
     * @param num
     * @return
     */
    public String generateRandom(int num) {
        String chars = "0123456789";
        StringBuffer number = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int rand = (int) (Math.random() * 10);
            number = number.append(chars.charAt(rand));
        }
        return number.toString();
    }
}
